package mornd.test2;

import org.springframework.cglib.core.Signature;
import org.springframework.cglib.reflect.FastClass;

import java.lang.reflect.InvocationTargetException;

/**
 * @author: mornd
 * @dateTime: 2023/5/6 - 15:36
 */
public class TargetFastClass extends FastClass {

    public TargetFastClass() {
        super(null);
    }

    private static Signature signature0 = new Signature("save", "()V");
    private static Signature signature1 = new Signature("save", "(I)V");
    private static Signature signature2 = new Signature("save", "(J)V");

    /**
     * 获取目标方法的编号
     * @param signature
     * @return
     */
    @Override
    public int getIndex(Signature signature) {
        if(signature0.equals(signature)) {
            return 0;
        } else if(signature1.equals(signature)) {
            return 1;
        } else if(signature2.equals(signature)) {
            return 2;
        } else {
            return -1;
        }
    }

    /**
     * 根据目标方法编号，正常调用目标方法
     * @param index
     * @param target
     * @param args
     * @return
     * @throws InvocationTargetException
     */
    @Override
    public Object invoke(int index, Object target, Object[] args) throws InvocationTargetException {
        if(index == 0) {
            ((Target) target).save();
            return null;
        } else if(index == 1) {
            ((Target) target).save((int) args[0]);
            return null;
        } else if(index == 2) {
            ((Target) target).save((long) args[0]);
            return null;
        } else {
            throw new RuntimeException("noSuchIndex：" + index);
        }
    }

    public static void main(String[] args) throws Exception {
        Target t = new Target();
        TargetFastClass fc = new TargetFastClass();
        int index = fc.getIndex(new Signature("save", "()V"));
        System.out.println("before");
        Object invoke = fc.invoke(index, t, null);
    }

    @Override
    public int getIndex(String s, Class[] classes) {
        return 0;
    }

    @Override
    public int getIndex(Class[] classes) {
        return 0;
    }

    @Override
    public Object newInstance(int i, Object[] objects) throws InvocationTargetException {
        return null;
    }

    @Override
    public int getMaxIndex() {
        return 0;
    }
}
